package com.qcc.week11.redislock;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Collections;

/**
 * @创建人 qianchengcheng
 * @创建时间 2022/3/27
 * @描述
 */
public class RedisLock {

    public static RedisLock getInstance(){
        return new RedisLock();
    }

    private JedisPool jedisPool = new JedisPool();

    /**
    *@描述 加锁
    *@参数 [lockValue, seconds]
    *@返回值 boolean
    *@创建人 qianchengcheng
    *@创建时间 2022/3/27
    *@修改人和其它信息
    */
    public boolean lock(String lockValue, int seconds) {
        try(Jedis jedis = jedisPool.getResource()) {
            return "OK".equals(jedis.set(lockValue, lockValue, "NX", "EX", seconds));
        }
    }

    /**
    *@描述 释放锁
    *@参数 [lock]
    *@返回值 boolean
    *@创建人 qianchengcheng
    *@创建时间 2022/3/27
    *@修改人和其它信息
    */
    public boolean release(String lock) {
        // lua脚本
        String luaScriptStr = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end";
        try(Jedis jedis = jedisPool.getResource()) {
            return jedis.eval(luaScriptStr, Collections.singletonList(lock), Collections.singletonList(lock)).equals(1L);
        }
    }
}
